package com.tceasy.gateway.controller;

import com.tceasy.common.utils.date.DateUtils;
import com.tceasy.common.utils.json.JsonUtil;
import com.tceasy.common.utils.string.StringUtil;
import com.tceasy.gateway.aop.Check;
import com.tceasy.gateway.api.Response;
import com.tceasy.gateway.domain.OpenService;
import com.tceasy.gateway.help.ExcelHelp;
import com.tceasy.gateway.service.MethodService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created by zhanghuan on 2016/4/11.
 * 接口相关操作
 */
@Check
@Controller
@RequestMapping(value = "/service",produces = { "application/json;charset=UTF-8" })
public class ServiceController {
    Logger logger = LoggerFactory.getLogger(ServiceController.class);
    @Autowired
    MethodService methodService;

    @RequestMapping("/add")
    @ResponseBody
    public Object add(OpenService openService){
        methodService.add(openService);
        return Response.SUCCESS("添加成功").toJson();
    }


    /**
     * 删除接口
     * @param method
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(String method){
        try {
            methodService.delete(method);
            return Response.SUCCESS("删除成功").toJson();
        } catch (Exception e) {
            return Response.BUSINESS_FAIL(e.getMessage()).toJson();
        }
    }

    /**
     * 关闭接口
     * @param method
     * @return
     */
    @RequestMapping("/stop")
    @ResponseBody
    public Object stop(String method){
        methodService.close(method);
        return Response.SUCCESS("已关闭").toJson();
    }

    @RequestMapping(value = "/export")
    public void exportExcel(HttpServletResponse response, HttpServletRequest request)throws Exception{
        String data = request.getParameter("data").toString();
        data = convertCoding(data);
        logger.info("导出接口列表的参数data:{}",data);
        Map map = JsonUtil.toMap(data);
        String matcher =  map.get("matcher") == null ? null:map.get("matcher").toString();
        String orderBy = map.get("orderBy") == null ? null:map.get("orderBy").toString();
        String[] columns =  map.get("columns") == null ? null: ((String)map.get("columns")).split(",");
        String columnsStr = map.get("columnTxt") == null ? null: ((String) map.get("columnTxt"));

        if(columns == null || columns.length == 0){
            logger.info("选择的字段不能为空");
            return;
        }
        if(StringUtil.isBlank(columnsStr)){
            logger.info("字段名称不能为空");
            return;
        }
        String[] columnsTxt = null;
        if(!StringUtil.isBlank(columnsStr)){
            columnsTxt = columnsStr.split(",");
        }
         /*记录列表*/
        List<OpenService> openServices=methodService.find(matcher, orderBy);
        ExcelHelp<OpenService> openServiceExcelHelp = new ExcelHelp<>(OpenService.class);
        String fileName ="接口列表";
        openServiceExcelHelp.dowloadExcel(openServices, columns,columnsTxt,fileName,response);
    }

    private String convertCoding(String str) throws UnsupportedEncodingException {
        if(StringUtil.isEmpty(str)){
            return null;
        }
        return new String(str.getBytes("iso-8859-1"), "utf-8");
    }


    /**
		 * 开启接口
		 * @param method
		 * @return
		 */
    @RequestMapping("/open")
    @ResponseBody
    public Object open(String method){
        methodService.open(method);
        return Response.SUCCESS("已开启").toJson();
    }

    @RequestMapping("/updateUI")
    public String updateUI(@RequestParam(value = "method", required = true) String method, Model model){
        OpenService openService=methodService.findOne(method);
        model.addAttribute("openService",openService);
        return "service/update";
    }

    /**
     * 修改接口
     * @param method 接口标识，非空
     * @param service 需要修改的内容以key=value&形式拼接
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public Object update(String method,OpenService service){
        methodService.update(method,service);
        return Response.SUCCESS("修改成功").toJson();
    }


    /**
     * 根据接口标识查询接口
     * @param method 接口标识，非空
     * @return
     */
    @RequestMapping("/getByMethod/{method:.+}")
    @ResponseBody
    public Object getByMethod(@PathVariable  String method){
        Assert.hasText(method,"接口标识不能为空");
        OpenService service=methodService.findOne(method);
        if(service==null){
            return Response.BUSINESS_FAIL("接口不存在").toJson();
        }
        return Response.SUCCESS().put("result",service).toJson();
    }

    /**
     * 分页查询
     * @param map 查询条件和排序条件
     * matcher 查询条件，json格式，eg:{partner:1212,name:xxx,email:xxxx@web.com}
     * orderBy 排序（可为空）允许多个字段参与排序，1代表正序，-1代表倒序，eg:{partner:-1,createDate:-1}
     * @param start 指定开始行数
     * @return
     */
    @RequestMapping("/query")
    @ResponseBody
    public Object query(@RequestParam(required = false) Map<String,String> map,@RequestParam(required = false,defaultValue = "0") int start){
        String matcher=map.get("matcher");
        String orderBy=map.get("orderBy");
        matcher=matcher==null?"":matcher;
         /*记录列表*/
        List<OpenService> list=methodService.findByPage(matcher, orderBy, start);
        /*总页数*/
        int pageCount=methodService.getPageCount(matcher);
        /*满足条件的记录总数*/
        long count=methodService.count(matcher);
        return Response.SUCCESS().put("result",list).put("count",count).put("pageCount",pageCount).toJson();
    }

    /**
     * 查询
     * @param map 查询条件和排序条件
     * matcher 查询条件，json格式，eg:{partner:1212,name:xxx,email:xxxx@web.com}
     * orderBy 排序（可为空）允许多个字段参与排序，1代表正序，-1代表倒序，eg:{partner:-1,createDate:-1}
     * @return
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public Object queryAll(@RequestParam(required = false) Map<String,String> map){
        String matcher=map.get("matcher");
        String orderBy=map.get("orderBy");
        matcher=matcher==null?"":matcher;
         /*记录列表*/
        List<OpenService> list=methodService.find(matcher, orderBy);
        return Response.SUCCESS().put("result",list).toJson();
    }
}
